<template>
	<view class="initialUserInfo">
		<login-navigation-bar title="个性化设置"></login-navigation-bar>
		<view class="initialUserInfoBox">
			<bottom-rect type="login"></bottom-rect>

			<view class="initialUserInfoForm">
				<!-- 标题 -->
				<view class="title main-font-color font-weight-bold">
					<text>你好，{{name}}</text>
					<text>欢迎使用韶大失物招领平台</text>
				</view>
				<form @submit="changeUserInfo">
					<!-- 头像和昵称 -->
					<view class="userInfo">
						<button open-type="chooseAvatar" @chooseavatar="changeAvatar">
							<image :src="avatarUrl_temp" mode="aspectFill"></image>
						</button>
						<input name="nickname" class="main-font-color font-weight-bold" @blur="changeNickname"
							type="nickname" :value="nickname" placeholder="用户昵称" placeholder-class="input" />
					</view>
					<!-- 提示 -->
					<view class="tips">
						<text>首次登录需要设置头像和昵称</text>
						<text>昵称不能为空且不得超过10个字</text>
						<text>（包括中文、英文和空格）</text>
					</view>
					<!-- 确定按钮 -->
					<button :class="[!isUseable?'disable':'btnConfirm btn-bgcolor']" hover-class="btn-click"
						:disabled="!isUseable" form-type="submit">开始使用</button>
				</form>
			</view>

		</view>
	</view>
</template>

<script>
	import loginNavigationBar from '@/components/login_navigationBar/login_navigationBar.vue'
	import bottomRect from '@/components/bottomRect/bottomRect.vue'

	import {
		setTokenStorage
	} from '@/subpkg/tim/utils/token.js';
	import logger from '@/subpkg/tim/utils/logger.js';
	import {
		genTestUserSig
	} from '@/subpkg/tim/debug/GenerateTestUserSig.js';
	const {
		getTokenStorage
	} = require('@/subpkg/tim/utils/token.js');
	const app = getApp()

	export default {
		name: 'initialUserInfo',
		components: {
			loginNavigationBar,
			bottomRect
		},
		data() {
			return {
				// 用户真实名字
				name: '',
				// 用户昵称
				nickname: '用户昵称',
				// 暂存的用户头像
				avatarUrl_temp: '/static/login/defaultAvatar.png',
				// 用户头像
				avatarUrl: '',
				// 确定按钮是否可用
				isUseable: false,
				// 聊天室的唯一标识userID
				userID:''
			}
		},
		methods: {
			// tim - 登录
			tim_login() {
				return new Promise(resolve => {
					const userID = this.userID;
					const userSig = genTestUserSig(userID).userSig;
					const SDKAppID = app.globalData.SDKAppID;
					logger.log(`TUI-login | login  | userSig:${userSig} userID:${userID}`);
					uni.$aegis.reportEvent({
						name: 'platform',
						ext1: 'platform-MP-WEIXIN',
						ext2: 'uniTuikitExternal',
						ext3: `${SDKAppID}`,
					})
					app.globalData.TIMuserInfo = {
						userSig,
						userID
					};
					setTokenStorage({
						TIMuserInfo: app.globalData.TIMuserInfo
					});
					wx.setStorageSync(`TIM_${getApp().SDKAppID}_isTUIKit`, true);
					uni.$TUIKit.login({
						userID: userID,
						userSig: userSig
					}).then(() => {
						uni.$aegis.reportEvent({
							name: 'login',
							ext1: 'login-success',
							ext2: 'uniTuikitExternal',
							ext3: `${SDKAppID}`,
						})
					}).catch((error) => {
						uni.$aegis.reportEvent({
							name: 'login',
							ext1: `login-failed#error:${error}`,
							ext2: 'uniTuikitExternal',
							ext3: `${SDKAppID}`,
						})
					})
					resolve()
				})
			},

			// 换头像
			changeAvatar(e) {
				this.avatarUrl_temp = e.detail.avatarUrl
				this.isFinishChange()
			},

			// 换昵称
			changeNickname(e) {
				this.nickname = e.detail.value.trim()
				if (this.nickname == '') {
					this.nickname = '用户昵称'
				}
				this.isFinishChange()
			},

			// 判断用户是否完成个性化设置
			isFinishChange() {
				if (this.avatarUrl_temp != '/static/login/defaultAvatar.png' && this.nickname != '用户昵称' && this.nickname !=
					'' && this.nickname.length != 0 && this.nickname.length <= 10) {
					this.isUseable = true
				} else {
					this.isUseable = false
				}
			},

			// 将用户头像与昵称上传到数据库以及本地缓存中
			updateUserInfo() {
				// 获取全局数据并将数据存到本地
				const userInfo = app.globalData.userInfo
				userInfo.nickname = this.nickname
				userInfo.avatarUrl = this.avatarUrl
				userInfo.userID = this.userID
				uni.setStorageSync('userInfo', userInfo)
				// 调用云函数，将数据存到数据库
				wx.cloud.callFunction({
					name: 'update_userBaseInfo',
					data: {
						student_ID: userInfo.profile.student_ID,
						nickname: this.nickname,
						avatarUrl: this.avatarUrl
					}
				}).then(res => {
					// console.log(res);
					uni.hideLoading()
					uni.switchTab({
						url: '/pages/index/index'
					})
				})
			},

			// 上传图片
			uploadAvatar() {
				// 随机生成云存储的图片名字
				let preName = app.uuid()
				let imgFormat = this.avatarUrl_temp.substring(this.avatarUrl_temp.indexOf('.'))
				let imgName = preName + imgFormat
				// 上传头像图片
				wx.cloud.uploadFile({
					cloudPath: `user_info/avatarUrl_images/${imgName}`,
					filePath: this.avatarUrl_temp
				}).then(res => {
					console.log(res);
					this.avatarUrl = res.fileID
					// 调用云函数
					this.updateUserInfo()
				})
			},

			// 获取openid作为聊天的userID唯一标识
			get_openid_as_userID() {
				return new Promise(resolve => {
					wx.cloud.callFunction({
						name: 'get_openid_as_userID'
					}).then(res => {
						resolve(res)
					})
				})
			},

			// 提交已修改的信息，并进入首页
			changeUserInfo() {
				uni.showLoading({
					title: '加载中...'
				})
				// 先获取openid
				this.get_openid_as_userID().then(res => {
					// 然后使用openid作为userID来登录
					this.userID = res.result.userInfo.openId
					app.globalData.userInfo.userID = this.userID
					this.tim_login().then(() => {
						this.uploadAvatar()
					})
				})
			}
		},
		onLoad() {
			// 获取以用户真实姓名
			this.name = app.globalData.userInfo.profile.name
		}
	}
</script>

<style scoped lang="scss">
	button::after {
		border: none;
	}

	/deep/ .input {
		color: #5e5d61;
	}

	// 按钮弃用样式
	.disable {
		color: white;
		width: 580rpx;
		height: 90rpx;
		border-radius: 16rpx;
		margin-top: 40rpx;
	}

	.initialUserInfoBox {
		display: flex;
		flex-direction: column;
		align-items: center;

		.initialUserInfoForm {
			overflow: hidden;
			background-color: white;
			width: 700rpx;
			height: 1000rpx;
			border-radius: 20rpx;
			box-shadow: 0 0 8px #b8b8b8;
			margin-top: -90rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.title {
				font-size: 50rpx;
				display: flex;
				flex-direction: column;
				width: 600rpx;
				margin-bottom: 40rpx;
				margin-top: 90rpx;
			}

			.userInfo {
				margin-bottom: 40rpx;

				button {
					width: 200rpx;
					height: 200rpx;
					border-radius: 10rpx;
					margin-bottom: 52rpx;

					image {
						width: 200rpx;
						height: 200rpx;
						margin-left: -28rpx;
					}
				}

				input {
					font-size: 50rpx;
					height: 60rpx;
					line-height: 50rpx;
					text-align: center;
				}
			}

			.tips {
				display: flex;
				flex-direction: column;
				align-items: center;
				color: #999999;
				font-size: 32rpx;
			}

			.btnConfirm {
				color: white;
				width: 580rpx;
				height: 90rpx;
				border-radius: 16rpx;
				margin-top: 40rpx;
			}
		}
	}
</style>
